<script>
export default {
  onLaunch() {
    console.log('App Launch');
    
    // 初始化本地数据库
    this.initLocalDatabase();
    
    // 检查登录状态
    this.checkLoginStatus();
  },
  onShow() {
    console.log('App Show');
  },
  onHide() {
    console.log('App Hide');
  },
  methods: {
    // 初始化本地数据库
    initLocalDatabase() {
      // 检查是否已初始化
      const isInitialized = uni.getStorageSync('furniture_db_initialized');
      if (isInitialized) {
        console.log('本地家具数据已初始化');
        return;
      }
      
      console.log('初始化本地家具数据库...');
      
      // 家具数据
      const furnitureData = [
        {
          _id: '5',
          name: '国标红木黑酸枝新中式沙发',
          price: '22998.66',
          sales: 7,
          imageUrl: '/static/home_furniture/sofa.jpg',
          tags: ['国标红木', '黑酸枝', '新中式'],
          description: '精选黑酸枝木料，传统工艺精制而成的新中式风格沙发',
          category: '沙发',
          material: '黑酸枝',
          style: '新中式',
          status: true
        },
        {
          _id: '6',
          name: '红木新中式红木古架多宝阁酸枝木客厅展示柜',
          price: '3268.66',
          sales: 35,
          imageUrl: '/static/home_furniture/cabinet.jpg',
          tags: ['酸枝木', '珠清古典', '仿红木家具'],
          description: '多宝阁设计，用于客厅展示收藏品',
          category: '架次',
          material: '酸枝木',
          style: '明清古典',
          status: true
        },
        {
          _id: '7',
          name: '红木酒柜实木置物中式南美酸枝木',
          price: '11970',
          sales: 0,
          imageUrl: '/static/home_furniture/wine-cabinet.jpg',
          tags: ['植物花卉', '可移动', '明清古典'],
          description: '中式南美酸枝木酒柜，植物花卉雕刻精美',
          category: '橱柜',
          material: '南美酸枝木',
          style: '明清古典',
          status: true
        },
        {
          _id: '8',
          name: '红木家具餐厅酒柜中式酒架墙壁柜',
          price: '31160',
          sales: 0,
          imageUrl: '/static/home_furniture/wine-rack.jpg',
          tags: ['植物花卉', '可移动', '明清古典'],
          description: '中式酒架墙壁柜，兼具实用与美观',
          category: '橱柜',
          material: '南美酸枝木',
          style: '明清古典',
          status: true
        }
      ];
      
      // 保存到本地存储
      try {
        uni.setStorageSync('furniture_data', furnitureData);
        uni.setStorageSync('furniture_db_initialized', true);
        console.log('本地家具数据库初始化完成');
      } catch (e) {
        console.error('本地数据库初始化失败:', e);
        uni.showToast({
          title: '数据初始化失败',
          icon: 'none'
        });
      }
    },
    
    // 检查登录状态
    async checkLoginStatus() {
      try {
        // 获取登录状态
        const token = uni.getStorageSync('uni_id_token');
        const userInfo = uni.getStorageSync('userInfo');
        
        // 检查是否已登录
        if (token && userInfo) {
          // 验证token有效性
          const valid = await this.validateToken(token);
          
          if (valid) {
            // 已登录且token有效，跳转到首页
            uni.switchTab({
              url: '/pages/home/index'
            });
          } else {
            // token无效，清除存储并跳转到登录页
            this.clearLoginData();
            this.navigateToLogin();
          }
        } else {
          // 未登录，跳转到登录页
          this.navigateToLogin();
        }
      } catch (e) {
        console.error('登录状态检查失败:', e);
        this.navigateToLogin();
      }
    },
    
    // 验证token有效性
    async validateToken(token) {
      try {
        // 调用云函数验证token
        const res = await uniCloud.callFunction({
          name: 'uni-id-cf',
          data: {
            action: 'checkToken',
            token: token
          }
        });
        
        return res.result.code === 0;
      } catch (e) {
        console.error('token验证失败:', e);
        return false;
      }
    },
    
    // 清除登录数据
    clearLoginData() {
      // 清除所有登录相关数据
      uni.removeStorageSync('uni_id_token');
      uni.removeStorageSync('userInfo');
      uni.removeStorageSync('uni_id_token_expired');
    },
    
    // 跳转到登录页
    navigateToLogin() {
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/users/login'
      });
    }
  }
}
</script>

<style>
/* 全局样式 */
page {
  background-color: #f8f3ed;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  color: #5c3c1c;
}

/* 按钮基础样式 */
button {
  border-radius: 8rpx;
  font-size: 32rpx;
}

button[type="primary"] {
  background-color: #5c3c1c;
  color: white;
}

button[type="default"] {
  background-color: #e8c39e;
  color: #5c3c1c;
}

/* 输入框基础样式 */
input, textarea {
  background-color: white;
  border: 1rpx solid #e8c39e;
  border-radius: 8rpx;
  padding: 15rpx 20rpx;
  font-size: 28rpx;
}

/* 全局图标颜色 */
.uni-icons {
  color: #5c3c1c;
}

/* 全局加载样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-spinner {
  animation: rotate 1s linear infinite;
}

.loading-text {
  font-size: 32rpx;
  color: #5c3c1c;
  margin-top: 20rpx;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 全局错误提示 */
.error-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  padding: 40rpx;
}

.error-icon {
  font-size: 60rpx;
  color: #e64340;
  margin-bottom: 20rpx;
}

.error-text {
  font-size: 32rpx;
  color: #e64340;
  text-align: center;
  margin-bottom: 30rpx;
}

.retry-btn {
  width: 200rpx;
  height: 70rpx;
  line-height: 70rpx;
  background-color: #5c3c1c;
  color: white;
  border-radius: 35rpx;
  font-size: 28rpx;
}
</style>